﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using DG.Tweening;
public class PlayerController : MonoBehaviour
{
    private SpriteRenderer player;
    private Rigidbody2D player_Rigi;
    private Vector3 mousePos;
    private bool isMoveLeft;
    private GameObject lastHitCommonPlatform;// 上一个射线检测到的一般平台（确保一个平台只加分一次）

    private float jumpHeight = 0.8f;// 玩家跳跃y轴高度
    private Vector3 currentPlatformPos;// 玩家当前所在平台位置    
    private Vector3 nextPlatformLeft, nextPlatformRight;// 玩家所在平台的下一个平台位置

    private Transform rayDown, rayLeft, rayRight;
    public LayerMask commonLayer, obstacleLayer, spikeLayer;// 平台的图层

    private void Start()
    {
        EventCenter.AddListener<int>(CL.EventType.InitPlayerControllerPropertyData, InitPlayerControllerPropertyData);


        player = GetComponent<SpriteRenderer>();
        player_Rigi = GetComponent<Rigidbody2D>();
        rayDown = transform.Find("rayDown");
        rayLeft = transform.Find("rayLeft");
        rayRight = transform.Find("rayRight");

        InitPlayerControllerPropertyData(0);
        //平台还未生成，先隐藏玩家，等进入UIGame后激活
        gameObject.SetActive(false);
    }

    private void OnDestroy()
    {
        EventCenter.RemoveListener<int>(CL.EventType.InitPlayerControllerPropertyData, InitPlayerControllerPropertyData);
    }

   
    /// <summary>
    /// 玩家控制脚本属性初始化
    /// </summary>
    private void InitPlayerControllerPropertyData(int indexSkin)
    {
        gameObject.SetActive(true);       
        gameObject.transform.position = new Vector3(0, -1.8f, 0);
        player.sprite = ResManager.Instance.playerControllerSkin[indexSkin];
        player.sortingLayerName = "Player";
        player.flipX = false;
        GetComponent<Collider2D>().enabled = true;

        lastHitCommonPlatform = null;
    }


    private void Update()
    {
        //是否为游戏状态
        if (GameManager.Instance.isGameControl && !GameManager.Instance.isGameOver)
        {
            if (Input.GetMouseButtonDown(0))
            {
                if (!DataManager.Instance.mGameData.isJumping && nextPlatformLeft != Vector3.zero && nextPlatformRight != Vector3.zero)
                {
                    mousePos = Input.mousePosition;
                    //防止点击暂停会触发跳跃
                    if (mousePos.y <= Screen.height / 1.1f)
                    {
                        DataManager.Instance.mGameData.isJumping = true;
                        DataManager.Instance.mGameData.isStartDrop = true;
                        SpawnManager.Instance.DecidePath();
                        SpawnManager.Instance.RandomExceptCommonPlatform();
                        //点击左边屏幕
                        if (mousePos.x <= Screen.width / 2)
                        {
                            isMoveLeft = true;
                        }
                        //点击右边屏幕
                        else
                        {
                            isMoveLeft = false;
                        }
                        Jump();
                    }
                }
            }
        }


        //判断GameOver
        if (!GameManager.Instance.isGameOver)
        {
            if (DataManager.Instance.mGameData.isJumping && (IsRayObstacle() || IsRaySpike()))
            {
                AudioManager.Instance.PlaySound("hit", 0.5f);
                PlayerDie();
                GameManager.Instance.OnGameOver();
                GameManager.Instance.UIGameOverOpen();                
            }
            else if (player_Rigi.velocity.y < 0 && !IsRayCommon())
            {
                AudioManager.Instance.PlaySound("fall");
                Invoke("PlayerDie", 2);
                GameManager.Instance.OnGameOver();
                //******玩家跳空后立即触发协程延迟两秒UIGameOverOpen，与玩家碰撞BottomWall  协程延迟两秒UIGameOverOpen重叠导致BUG******
                GameManager.Instance.UIGameOverOpen();
                player.sortingLayerName = "Default";
                GetComponent<Collider2D>().enabled = false;
            }
        }
    }

    /// <summary>
    /// 玩家跳跃
    /// </summary>
    private void Jump()
    {
        AudioManager.Instance.PlaySound("jump");
        if (isMoveLeft)
        {
            player.flipX = true;
            transform.DOMoveX(nextPlatformLeft.x, 0.2f);
            transform.DOMoveY(nextPlatformLeft.y + jumpHeight, 0.15f);
        }
        else
        {
            player.flipX = false;
            transform.DOMoveX(nextPlatformRight.x, 0.2f);
            transform.DOMoveY(nextPlatformRight.y + jumpHeight, 0.15f);
        }
    }
    /// <summary>
    /// 玩家死亡
    /// </summary>
    private void PlayerDie()
    {
        SpawnManager.Instance.SpawnPlayerDieEffect(transform.position);
        //用隐藏代替摧毁，因为玩家不是克隆的，至始至终只有一个
        gameObject.SetActive(false);
    }


    #region 射线检测
    /// <summary>
    /// 是否射线检测到一般平台
    /// </summary>
    /// <returns></returns>
    private bool IsRayCommon()
    {
        //射线长度必须大于游戏角色跳跃高度（1 > 0.8f）
        RaycastHit2D hit = Physics2D.Raycast(rayDown.position, Vector2.down, 1f, commonLayer);
        if (hit.collider != null)
        {
            if (hit.collider.tag == "CommonPlatform")
            {
                //刚开始不能记分
                if (lastHitCommonPlatform == null)
                {
                    lastHitCommonPlatform = hit.collider.gameObject;
                    return true;
                }
                if (lastHitCommonPlatform != hit.collider.gameObject)
                {
                    DataManager.Instance.AddScore();
                    lastHitCommonPlatform = hit.collider.gameObject;
                }
                return true;
            }
        }
        return false;
    }
    /// <summary>
    /// 是否射线检测到障碍物
    /// </summary>
    /// <returns></returns>
    private bool IsRayObstacle()
    {
        RaycastHit2D hitLeft = Physics2D.Raycast(rayLeft.position, Vector2.left, 0.05f, obstacleLayer);
        RaycastHit2D hitRight = Physics2D.Raycast(rayRight.position, Vector2.right, 0.05f, obstacleLayer);
        if (hitLeft.collider != null)
        {
            if (hitLeft.collider.tag == "ObstaclePlatform")
            {
                return true;
            }
        }
        if (hitRight.collider != null)
        {
            if (hitRight.collider.tag == "ObstaclePlatform")
            {
                return true;
            }
        }
        return false;
    }
    /// <summary>
    /// 是否射线检测到钉子平台
    /// </summary>
    /// <returns></returns>
    private bool IsRaySpike()
    {
        RaycastHit2D hitLeft = Physics2D.Raycast(rayLeft.position, Vector2.left, 0.05f, spikeLayer);
        RaycastHit2D hitRight = Physics2D.Raycast(rayRight.position, Vector2.right, 0.05f, spikeLayer);
        if (hitLeft.collider != null)
        {
            if (hitLeft.collider.tag == "SpikePlatform")
            {
                return true;
            }
        }
        if (hitRight.collider != null)
        {
            if (hitRight.collider.tag == "SpikePlatform")
            {
                return true;
            }
        }
        return false;
    }
    #endregion


    public void OnTriggerEnter2D(Collider2D collision)
    {
        switch (collision.tag)
        {
            case "CommonPlatform":
                DataManager.Instance.mGameData.isJumping = false;
                currentPlatformPos = collision.gameObject.transform.position;
                nextPlatformLeft = new Vector3(currentPlatformPos.x - SpawnManager.Instance.nextXPos, currentPlatformPos.y + SpawnManager.Instance.nextYPos, currentPlatformPos.z);
                nextPlatformRight = new Vector3(currentPlatformPos.x + SpawnManager.Instance.nextXPos, currentPlatformPos.y + SpawnManager.Instance.nextYPos, currentPlatformPos.z);
                break;
            case "Diamond":
                AudioManager.Instance.PlaySound("diamond");
                ObjectPool.Instance.BackObj(collision.gameObject);
                DataManager.Instance.AddDiamond();
                break;
            //case "BottomWall":
            //    PlayerDie();
            //    GameManager.Instance.OnGameOver();
            //    GameManager.Instance.UIGameOverOpen();                
            //    break;
            default:
                break;
        }
    }

    
}
